package com.mvvm.ktnet.application

import android.app.Application
import android.content.Context
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.multidex.MultiDex
import com.effective.android.anchors.AnchorsManager
import com.effective.android.anchors.Project
import com.mvvm.ktnet.BuildConfig
import com.mvvm.ktnet.utils.AppUtil

/**
 *
 * @ProjectName:    KtNet
 * @Package:        com.mvvm.ktnet.application
 * @ClassName:      app
 * @Description:     java类作用描述
 * @Author:         Alex
 * @CreateDate:     2020/11/7 15:58
 * @UpdateUser:     更新者：
 * @UpdateDate:     2020/11/7 15:58
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
class App : Application(), ViewModelStoreOwner {


    companion object {
        lateinit var context: App
    }

    init {
        context = this
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }


    override fun onCreate() {
        super.onCreate()
        mAppViewModelStore = ViewModelStore()


        val processName = AppUtil.currentProcessName
        if (processName == packageName) {
            // 主进程初始化
            onMainProcessInit()
        } else {
            // 其他进程初始化
            processName?.let { onOtherProcessInit(it) }
        }




    }


    open fun onMainProcessInit() {
        /**
         * @description  代码的初始化请不要放在oncreate直接操作，按照下面新建异步方法
         */
        AnchorsManager.getInstance()
            .debuggable(BuildConfig.DEBUG)
            //设置锚点
            .addAnchor(
                InitNetWork.TASK_ID,
                InitUtils.TASK_ID,
                InitMMKV.TASK_ID,
                InitLoading.TASK_ID
            )
            .start(
                Project.Builder("app", AppTaskFactory())
                    .add(InitNetWork.TASK_ID)
                    .add(InitMMKV.TASK_ID)
                    .add(InitUtils.TASK_ID)
                    .add(InitLoading.TASK_ID)
                    .build()
            )
    }

    /**
     * 其他进程初始化，[processName] 进程名
     */
    open fun onOtherProcessInit(processName: String) {}


    private lateinit var mAppViewModelStore: ViewModelStore
    private var mFactory: ViewModelProvider.Factory? = null
    override fun getViewModelStore(): ViewModelStore {
        return mAppViewModelStore
    }
    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, this.getAppFactory())
    }

    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }

}